package org.example.servlet;

import org.example.DAO.BlogDAO;
import org.example.entity.Blog;
import org.example.DAO.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {

    // 记录参数信息
    private void logParameters(HttpServletRequest request) {
        System.out.println("\n=== 请求参数信息 ===");
        request.getParameterMap().forEach((key, values) -> {
            if ("content".equals(key)) {
                System.out.println(key + " = [内容长度:" + (values.length > 0 ? values[0].length() : 0) + "]");
            } else {
                System.out.println(key + " = " + String.join(", ", values));
            }
        });
        System.out.println("========================\n");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logParameters(request);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String blogId = request.getParameter("blogId");
        System.out.println("获取日志详情，blogId：" + blogId);

        if (blogId != null && !blogId.isEmpty()) {
            getBlogById(blogId, response);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write("{\"success\":false,\"message\":\"缺少blogId参数\"}");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logParameters(request);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        // 解析请求参数
        String action = request.getParameter("action");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String blogId = request.getParameter("blogId");

        // 处理添加操作
        if ("add".equals(action)) {
            addBlog(request, response, title, content);
        }
        // 处理更新操作
        else if ("update".equals(action)) {
            updateBlog(request, response, blogId, title, content);
        }
        // 其他操作
        else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write("{\"success\":false,\"message\":\"无效的操作类型\"}");
        }
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 已弃用，所有操作通过POST处理
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.write("{\"success\":false,\"message\":\"请使用POST请求并指定action参数\"}");
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logParameters(request);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String blogId = request.getParameter("blogId");
        System.out.println("DELETE请求收到的blogId: " + blogId);

        if (blogId == null || blogId.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write("{\"success\":false,\"message\":\"缺少blogId参数\"}");
            return;
        }

        HttpSession session = request.getSession(false);
        if (session == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write("{\"success\":false,\"message\":\"用户未登录\"}");
            return;
        }

        Object userIdObj = session.getAttribute("userId");
        String userId = userIdObj != null ? userIdObj.toString() : null;

        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write("{\"success\":false,\"message\":\"用户信息获取失败\"}");
            return;
        }

        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            BlogDAO blogDAO = new BlogDAO(conn);

            // 获取博客并验证所有权
            Blog blog = blogDAO.getBlogById(blogId);
            if (blog == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.write("{\"success\":false,\"message\":\"找不到指定的博客\"}");
                return;
            }

            if (!blog.getUserId().equals(userId)) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                out.write("{\"success\":false,\"message\":\"无权限删除该博客\"}");
                return;
            }

            // 删除博客
            boolean success = blogDAO.deleteBlog(blogId);
            if (success) {
                out.write("{\"success\":true,\"message\":\"删除成功\"}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.write("{\"success\":false,\"message\":\"删除失败\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("{\"success\":false,\"message\":\"数据库错误: " + escapeJson(e.getMessage()) + "\"}");
        } finally {
            DBUtil.close(conn);
        }
    }

    // 提取的更新方法
    private void updateBlog(HttpServletRequest request, HttpServletResponse response,
                            String blogId, String title, String content)
            throws IOException {
        logParameters(request);
        PrintWriter out = response.getWriter();

        System.out.println("更新请求收到的blogId：" + blogId);
        System.out.println("更新请求收到的title：" + title);
        System.out.println("更新请求收到的content：" + (content != null ? "长度：" + content.length() : "null"));

        // 验证输入
        if (title == null || title.trim().isEmpty()) {
            System.out.println("[错误] 标题为空");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write("{\"success\":false,\"message\":\"标题不能为空\"}");
            return;
        }

        if (content == null || content.trim().isEmpty()) {
            System.out.println("[错误] 内容为空");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write("{\"success\":false,\"message\":\"内容不能为空\"}");
            return;
        }

        HttpSession session = request.getSession(false);
        if (session == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write("{\"success\":false,\"message\":\"用户未登录\"}");
            return;
        }

        Object userIdObj = session.getAttribute("userId");
        String userId = userIdObj != null ? userIdObj.toString() : null;

        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write("{\"success\":false,\"message\":\"用户信息获取失败\"}");
            return;
        }

        // 更新博客内容
        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            BlogDAO blogDAO = new BlogDAO(conn);

            // 检查博客是否存在
            Blog blog = blogDAO.getBlogById(blogId);
            if (blog == null) {
                System.out.println("[错误] 找不到指定的博客: " + blogId);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.write("{\"success\":false,\"message\":\"找不到指定的博客\"}");
                return;
            }

            // 检查用户是否有权修改该博客
            if (!blog.getUserId().equals(userId)) {
                System.out.println("[错误] 用户无权修改博客: 当前用户=" + userId + ", 博客所有者=" + blog.getUserId());
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                out.write("{\"success\":false,\"message\":\"无权限修改该博客\"}");
                return;
            }

            // 更新博客内容
            blog.setTitle(title);
            blog.setContent(content);
            blog.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

            boolean result = blogDAO.updateBlog(blog);

            if (result) {

                out.write("{\"success\":true,\"message\":\"更新成功\"}");
            } else {
                System.out.println("[错误] 博客更新失败: " + blogId);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.write("{\"success\":false,\"message\":\"更新失败\"}");
            }
        } catch (SQLException e) {
            System.out.println("[错误] 数据库错误: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("{\"success\":false,\"message\":\"数据库错误: " + escapeJson(e.getMessage()) + "\"}");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    System.out.println("[警告] 关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    private void addBlog(HttpServletRequest request, HttpServletResponse response,
                         String title, String content) throws IOException {
        logParameters(request);
        PrintWriter out = response.getWriter();

        // 验证输入
        if (title == null || title.trim().isEmpty() ||
                content == null || content.trim().isEmpty()) {
            String error = "标题或内容不能为空";
            System.out.println("[添加错误] " + error);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write("{\"success\":false,\"message\":\"" + error + "\"}");
            return;
        }

        HttpSession session = request.getSession(false);
        if (session == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write("{\"success\":false,\"message\":\"用户未登录\"}");
            return;
        }

        Object userIdObj = session.getAttribute("userId");
        String userId = userIdObj != null ? userIdObj.toString() : null;

        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write("{\"success\":false,\"message\":\"用户信息获取失败\"}");
            return;
        }

        Blog newBlog = new Blog();
        newBlog.setBlogId("BLOG_" + System.currentTimeMillis());
        newBlog.setUserId(userId);
        newBlog.setTitle(title);
        newBlog.setContent(content);
        newBlog.setViewCount(0);
        newBlog.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        newBlog.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            BlogDAO blogDAO = new BlogDAO(conn);
            boolean success = blogDAO.addBlog(newBlog);

            if (success) {
                // 确保返回有效的JSON
                out.write("{\"success\":true,\"message\":\"发布成功\"}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.write("{\"success\":false,\"message\":\"发布失败\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("{\"success\":false,\"message\":\"数据库错误: " + escapeJson(e.getMessage()) + "\"}");
        } finally {
            DBUtil.close(conn);
        }
    }

    private void getBlogById(String blogId, HttpServletResponse response) throws IOException {
        Connection conn = null;
        PrintWriter out = response.getWriter();
        try {
            conn = DBUtil.getConnection();
            BlogDAO blogDAO = new BlogDAO(conn);
            Blog blog = blogDAO.getBlogById(blogId);

            System.out.println("查询日志详情，blogId=" + blogId + "，结果：" + (blog != null ? "找到" : "未找到"));

            if (blog != null) {
                // 更新浏览量
                blogDAO.incrementViewCount(blogId);

                // 返回博客详情
                out.print("{\"success\":true,\"blog\":{");
                out.print("\"blogId\":\"" + blog.getBlogId() + "\",");
                out.print("\"userId\":\"" + blog.getUserId() + "\",");
                out.print("\"title\":\"" + escapeJson(blog.getTitle()) + "\",");
                out.print("\"content\":\"" + escapeJson(blog.getContent()) + "\",");
                out.print("\"viewCount\":" + blog.getViewCount() + ",");
                out.print("\"status\":" + blog.getStatus() + ",");
                out.print("\"createdAt\":\"" + blog.getCreatedAt() + "\",");
                out.print("\"updatedAt\":\"" + blog.getUpdatedAt() + "\"");
                out.print("}}");
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.write("{\"success\":false,\"message\":\"找不到指定的博客\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("{\"success\":false,\"message\":\"数据库错误: " + escapeJson(e.getMessage()) + "\"}");
        } finally {
            DBUtil.close(conn);
        }
    }
    // 添加JSON转义方法，解决响应格式问题
    private String escapeJson(String input) {
        if (input == null) return "";
        return input
                .replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}